package com.mongo.secret;

import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * 提供Rsa加解密
 * @author xiazhun
 * @create 2022/9/20
 */
@NoArgsConstructor
public class Rsa implements Secret{

    private static volatile Rsa INSTANCE;

    public static Rsa getInstance() {
        if (INSTANCE == null) {
            //同步
            synchronized (Rsa.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Rsa();
                }
            }
        }
        return INSTANCE;
    }
    @Override
    public String encrypt(String data) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String encrypt(String data, String publicKey) {
        Assert.notNull(publicKey,"publicKey can not be null");
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        String outStr;
        try {
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        }catch (Exception e){
            throw new IllegalArgumentException(e.getMessage());
        }
        return outStr;
    }

    @Override
    public String decode(String data) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String decode(String data, String key) {
        Assert.notNull(key,"privateKey can not be null");

        byte[] inputByte = Base64.getDecoder().decode(data);

        byte[] decoded = Base64.getDecoder().decode(key);
        String outStr;
        try {
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte), StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new IllegalArgumentException(e.getMessage());
        }
        return outStr;
    }
}
